package com.jxbeidou.login.controller;

import com.jxbeidou.core.entity.R;
import com.jxbeidou.core.util.IpUtils;
import com.jxbeidou.login.entity.JwtVO;
import com.jxbeidou.login.entity.LoginUserDTO;
import com.jxbeidou.login.service.LoginUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: jxbeidou-basic
 * @ClassName: AuthController
 * @description: 登录控制层
 * @author: 杜晓祥
 * @create: 2023-12-26 15:15
 * 版权所有：交信北斗(北京)信息科技有些公司
 */
@RestController
@RequestMapping(value = "/", consumes = MediaType.APPLICATION_JSON_VALUE)
@Validated
@Slf4j
@Tag(name = "鉴权接口")
public class AuthController {

    @Resource
    private LoginUserService loginUserService;

    @PostMapping(value = "token")
    @Operation(summary = "用户登录")
    public R<JwtVO> token (HttpServletRequest request, @RequestBody LoginUserDTO user) {
        String ip = IpUtils.getIpAddr(request);
        JwtVO jwtVO = loginUserService.generateToken(ip, user);
        return R.success(jwtVO);
    }

    @PostMapping(value = "logout")
    @Operation(summary = "用户登出")
    public R<String> logout (HttpServletRequest request) {
//        String token = HttpUtil.getToken(request);
        String ip = IpUtils.getIpAddr(request);
        boolean r = loginUserService.logout(ip);
        if (r) {
            return R.success("登出成功");
        }
        return R.failed("登出失败");
    }
}
